package predict.app.handler;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;


public class MainActivity extends AppCompatActivity {

    Button star, stop, barButton;
    Handler handler = new Handler();
    ProgressBar bar = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        star = (Button)findViewById(R.id.button);
        stop = (Button)findViewById(R.id.button2);
        barButton = (Button)findViewById(R.id.button3);
        bar = (ProgressBar)findViewById(R.id.progressBar);

        star.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.post(dayinshuju);   //开始线程
            }
        });

        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.removeCallbacks(dayinshuju);   //删除Runable，停止线程
                jindutiaoHandler.removeCallbacks(jindutiao);
            }
        });

        barButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bar.setVisibility(View.VISIBLE);
                jindutiaoHandler.post(jindutiao);
            }
        });
    }

    Handler jindutiaoHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            bar.setProgress(msg.arg1);
            jindutiaoHandler.post(jindutiao);
        }
    };

    Runnable dayinshuju = new Runnable() {
        @Override
        public void run() {
            System.out.print("打印出数据");
            Log.v("信息", "打印出东西");
            handler.postDelayed(dayinshuju, 2000);   //延迟多少秒运行
        }
    };

    Runnable jindutiao = new Runnable() {
        private int i = 0;
        @Override
        public void run() {
            System.out.print("开始更新进度条");
            i = i + 10;
            Message msg = jindutiaoHandler.obtainMessage();
            Log.v("信息", String.valueOf(i));
            msg.arg1 = i;
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
              //http://www.jianshu.com/p/8e8ac28f6c1a
            if( i == 110) {
                Log.v("信息", String.valueOf(i));
                jindutiaoHandler.removeCallbacks(jindutiao);
            } else {
                jindutiaoHandler.sendMessage(msg);
            }
        }
    };
}
